package com.fliangyun.nsa.nsamanage.controller;

import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.fliangyun.nsa.nsamanage.constant.CommonConstant;
import com.fliangyun.nsa.nsamanage.entities.AddCalendar;
import com.fliangyun.nsa.nsamanage.entities.CalendarInfo;
import com.fliangyun.nsa.nsamanage.entities.User;
import com.fliangyun.nsa.nsamanage.service.impl.CalendarInfoServiceImpl;
import com.fliangyun.nsa.nsamanage.service.impl.UserServiceImpl;
import com.fliangyun.nsa.nsamanage.utils.FileUtil;
import com.fliangyun.nsa.nsamanage.utils.ImageIoUtil;
import com.fliangyun.nsa.nsamanage.utils.StringUtil;
import com.fliangyun.nsa.nsamanage.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fuliangyun@139.com
 * @date 2023年05月30日
 * @description
 */
@Slf4j
@RestController
@RequestMapping(value = "api")
public class ApiIndexController {
    @Value("${nsa.base.folder}")
    String baseFileFolder;

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private CalendarInfoServiceImpl calendarInfoService;

    @GetMapping("listData")
    public Result<?> listData(Authentication authentication){
        List<CalendarInfo> calendarInfoList = calendarInfoService.findList(new CalendarInfo(), authentication);
        if (!CollectionUtils.isEmpty(calendarInfoList)) {
            // 检查生日是否已过

            Date nowDate = new Date();
            try {
                nowDate = DateUtils.parseDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd");
            } catch (ParseException e) {
                e.printStackTrace();
            }

            for (CalendarInfo calendarInfo : calendarInfoList) {
                if (CommonConstant.ONE.equals(calendarInfo.getType())){
                    // 新历
                    calendarInfo.setType("新历");
                    Calendar calendar = Calendar.getInstance();
                    Calendar birthday = Calendar.getInstance();
                    birthday.setTime(calendarInfo.getBirthday());
                    calendarInfo.setAge(calendar.get(Calendar.YEAR)-birthday.get(Calendar.YEAR));
                    // 设置当前年份
                    birthday.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
//                    calendarInfo.setDays((int) DateUtil.between(nowDate, birthday.getTime(), DateUnit.DAY));
                    calendarInfo.setDays(Math.round((birthday.getTimeInMillis() - nowDate.getTime()) / CommonConstant.DAYS));
                    if (calendarInfo.getDays() != 0){
                        if ((nowDate.getTime()-birthday.getTimeInMillis()) > 0){
                            calendarInfo.setPassFlag(true);
                            calendarInfo.setDays(9999L);
                        }else {
                            calendarInfo.setAge(calendarInfo.getAge()-1);
                        }
                    }
                    calendarInfo.setBirthdayLabel(DateFormatUtils.format(calendarInfo.getBirthday(), "yyyy年MM月dd日"));

                }else if (CommonConstant.TWO.equals(calendarInfo.getType())){
                    // 农历
                    ChineseDate now = new ChineseDate(new Date());
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(calendarInfo.getBirthday());
                    // 组装
                    ChineseDate date = new ChineseDate(now.getChineseYear(), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DATE));
                    calendarInfo.setAge(now.getChineseYear()-calendar.get(Calendar.YEAR));
                    Date birthday = date.getGregorianCalendar().getTime();
                    calendarInfo.setDays(Math.round((birthday.getTime() - nowDate.getTime()) / CommonConstant.DAYS));
                    if (calendarInfo.getDays() != 0){
                        if ((nowDate.getTime()-birthday.getTime()) > 0){
                            calendarInfo.setPassFlag(true);
                            calendarInfo.setDays(9999L);
                        }else {
                            calendarInfo.setAge(calendarInfo.getAge()-1);
                        }
                    }
                    // 组装
                    ChineseDate dd = new ChineseDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DATE));
                    calendarInfo.setBirthdayLabel(String.format("%s年%s%s", calendar.get(Calendar.YEAR), dd.getChineseMonth(), dd.getChineseDay()));
                    calendarInfo.setType("农历");
                }
            }
        }

        // 排序，按照最近生日排序
        calendarInfoList = calendarInfoList.stream().sorted(Comparator.comparing(CalendarInfo::getDays)).collect(Collectors.toList());
        return Result.success(calendarInfoList);
    }

    /**
     * 修改密码
     * @author fuliangyun@139.com
     * @date 2023-06-01 10:09
     * @param authentication
     * @param para
     * @return Result<?>
     */
    @PostMapping("savePassword")
    public Result<?> savePassword(Authentication authentication, User para){
        if (StringUtil.isBlank(para.getPassword())){
            return Result.fail("密码为空");
        }
        // 获取用户信息
        User user = (User) authentication.getPrincipal();
        user.setPassword(new BCryptPasswordEncoder().encode(para.getPassword()));
        userService.saveUser(user);
        return Result.success("密码修改成功", user);
    }

    /**
     * 保存日期
     * @author fuliangyun@139.com
     * @date 2023-06-01 10:09
     * @param authentication
     * @return Result<?>
     */
    @PostMapping("saveBirthday")
    public Result<?> saveBirthday(Authentication authentication, AddCalendar addCalendar){
        // 获取用户信息
        CalendarInfo calendarInfo = new CalendarInfo();
        BeanUtils.copyProperties(addCalendar, calendarInfo);
        try {
            Date d = DateUtils.parseDate(addCalendar.getBirthday(), "yyyy-MM-dd");
            calendarInfo.setBirthday(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendarInfoService.save(calendarInfo, authentication);
        return Result.success();
    }

    /**
     * 保存日期
     * @author fuliangyun@139.com
     * @date 2023-06-01 10:09
     * @param authentication
     * @return Result<?>
     */
    @PostMapping("removeBirthday")
    public Result<?> removeBirthday(Authentication authentication, AddCalendar addCalendar){
        // 获取用户信息
        calendarInfoService.delete(addCalendar.getId(), authentication);
        return Result.success("删除成功", null);
    }

    /**
     * 修改密码
     * @author fuliangyun@139.com
     * @date 2023-06-01 10:09
     * @param authentication
     * @return Result<?>
     */
    @PostMapping("savePhoto")
    public Result<?> savePhoto(Authentication authentication, MultipartFile file){
        if (file == null){
            return Result.fail("头像图片为空");
        }
        // 获取用户信息
        User user = (User) authentication.getPrincipal();
        String basePath = FileUtil.getPath(baseFileFolder, "photo");
        // 创建文件夹
        FileUtil.createFolder(basePath);

        // 保存图片
        String fileName = System.currentTimeMillis()+".png";
        File photo = new File(FileUtil.getPath(basePath, fileName));
        try {
            file.transferTo(photo);

            // 图片压缩
            String url = photo.getAbsolutePath();
            String suffix = url .substring(url.lastIndexOf(".") + 1);
            ImageIoUtil.compression(url, photo.getAbsolutePath(),1.5,0.1f,0.5f,suffix);
            user.setPhoto(FileUtil.getPath(FileUtil.BIAS,"file", "photo", fileName));
            userService.saveUser(user);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("头像修改失败");
        }
        return Result.success("头像修改成功", user);
    }
}
